package com.joy.conf.shiro;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joy.common.constant.CommonCons;
import com.joy.web.admin.entity.User;
import com.joy.web.admin.service.IResourceService;
import com.joy.web.admin.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @Description MyReal shiro授权，登录
 * @return
 * @Author yjzhao
 * @Date 2019/9/27 20:38
 **/
@Component
public class MyRealm extends AuthorizingRealm {

	public MyRealm(){
		super(new AllowAllCredentialsMatcher());
        setAuthenticationTokenClass(UsernamePasswordToken.class);

        ////FIXME: 暂时禁用Cache
        //setCachingEnabled(false);
	}

	@Resource
	private IUserService userService;
	@Resource
	private IResourceService resourceService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

		try{
            Set<String> shiroPermissions = resourceService.getPermissionsByUserNm(username);
            authorizationInfo.setStringPermissions(shiroPermissions);
        } catch(Exception e) {
		    e.printStackTrace();
		    return authorizationInfo;
        }

		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String userNm = (String) token.getPrincipal();
        User user;
        try {
			QueryWrapper<User> userQ = new QueryWrapper<User>()
					.eq("user_nm", userNm)
					.eq("del_yn", CommonCons.FlagType.N);
			user = userService.getOne(userQ, true);
        } catch (Exception e) {
		    e.printStackTrace();
		    throw new UnknownAccountException();
        }

        if (user == null) {
            throw new UnknownAccountException();// 没找到帐号
        }

		String password = new String((char[]) token.getCredentials());
		// 密码错误
		if (!SecureUtil.md5().digestHex(password).toUpperCase().equals(user.getUserPwd())) {
			throw new IncorrectCredentialsException();
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userNm, password, getName());

		return info;
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		super.clearCache(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		super.clearCachedAuthenticationInfo(arg0);
	}

	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		super.clearCachedAuthorizationInfo(arg0);
	}

	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}

	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}

	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}
}
